package cn.mangodai.controller;

import cn.mangodai.domain.User;
import cn.mangodai.service.UserService;
import cn.mangodai.vo.Message;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * RESTFULL Controller
 * MangoDai
 * 2017 09 23 8:56 PM
 */
@RestController
public class UserController {

    @Autowired
    UserService service;

    @Value("${registerMSG.content}")
    private String content;
    @Value("${registerMSG.start}")
    private String start;
    @Value("${registerMSG.end}")
    private String end;
    @Value("${registerMSG.sdf}")
    private String sdf;

    private volatile SimpleDateFormat dateFormat = null;

    /**
     * 判断请求是否超期
     *
     * @return
     */
    private boolean isExpire() {
        if (dateFormat == null) {
            dateFormat = new SimpleDateFormat(sdf);
        }
        String now = dateFormat.format(new Date());
        if (now.compareTo(start) >= 0 && now.compareTo(end) <= 0) {
            return false;
        } else {
            // expire
            return true;
        }
    }

    @RequestMapping(value = "/user/register")
    public String registerUser(User user) {
        Message msg = new Message();
        if (isExpire()) {
            msg.setState(200);
            msg.setMsg(content + " ：start " + start + " end " + end);
        } else {
            msg.setState(400);
            if (StringUtils.isBlank(user.getSchoolNumber())) {
                msg.setMsg("学号不可以为空");
            } else if (StringUtils.isBlank(user.getClasses())) {
                msg.setMsg("班级不可以为空");
            } else if (StringUtils.isBlank(user.getQqNumber())) {
                msg.setMsg("QQ号不可以为空");
            } else if (StringUtils.isBlank(user.getName())) {
                msg.setMsg("名字不可以为空");
            } else {
                user.setCreateTime(new Date());
                msg = service.register(user);
            }
        }
        return "callback(" + JSON.toJSONString(msg, SerializerFeature.PrettyFormat) + ")";
    }

    @RequestMapping(value = "/user/list")
    public String userList(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        List<User> users = service.getAllUser();
        return "callback(" + JSON.toJSONString(users) + ")";
    }
}
